package cn.lds.j368.dsbank.service.impl;

import cn.lds.j368.dsbank.constant.DsBankConstants;
import cn.lds.j368.dsbank.domain.LoanProduce;
import cn.lds.j368.dsbank.dto.RespDTO;
import cn.lds.j368.dsbank.exception.ServiceException;
import cn.lds.j368.dsbank.mapper.LoanProduceMapper;
import cn.lds.j368.dsbank.service.LoanProduceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Objects;

@Service
public class LoanProduceServiceImpl implements LoanProduceService {


    @Autowired
    private LoanProduceMapper loanProduceMapper;

    @Override
    public RespDTO<List<LoanProduce>> selectLoanProduceAll() throws ServiceException {
        List<LoanProduce> loanProduces = loanProduceMapper.selectLoanProduceAll();

        if (CollectionUtils.isEmpty(loanProduces)){
            throw new ServiceException(DsBankConstants.SysMsg.QUERY_FAIL);
        }
        return RespDTO.buildSuccess(loanProduces);
    }

    @Override
    public RespDTO<LoanProduce> selectLoanProduceByProduceId(Integer produceId) throws ServiceException {

        LoanProduce loanProduce = loanProduceMapper.selectLoanProduceByProduceId(produceId);

        if (Objects.isNull(loanProduce)){
            throw new ServiceException(DsBankConstants.SysMsg.QUERY_FAIL);
        }


        return RespDTO.buildSuccess(loanProduce);
    }

    @Override
    public RespDTO addOrModifyLoanProduce(LoanProduce loanProduce) throws ServiceException {

        //当参数没有id，我们认为是通过表单提交的对象那么我们做添加操作
        if (null == loanProduce.getLoanId()){
            int insert = loanProduceMapper.insert(loanProduce);
            if (insert <= 0){
                throw new ServiceException(DsBankConstants.SysMsg.ADD_DATA_FAIL);
            }
        }else {
            //如果参数中对象有id，代表数据已经存在与数据库，我们做修改处理
            int i = loanProduceMapper.updateById(loanProduce);
            if (i < 0){
                throw new ServiceException(DsBankConstants.SysMsg.MODIFY_DATA_FAIL);
            }
        }
        return RespDTO.buildSuccess();
    }

    @Override
    public RespDTO delLoanProduce(Integer produceId) throws ServiceException {

        int i = loanProduceMapper.deleteById(produceId);

        if (i <=0){
            throw new ServiceException(DsBankConstants.SysMsg.DEL_DATA_FAIL);
        }

        return RespDTO.buildSuccess();
    }
}
